package org.momo.rpc.serialize.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.momo.rpc.protocol.RpcRequest;
import org.momo.rpc.protocol.RpcResponse;
import org.momo.rpc.serialize.Serializer;

import java.io.IOException;

public class JsonSerializer implements Serializer {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public <T> byte[] serialize(T obj) throws IOException {
        return OBJECT_MAPPER.writeValueAsBytes(obj);
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) throws IOException {
        Object obj = OBJECT_MAPPER.readValue(bytes, clazz);
        if(clazz == RpcRequest.class) {
            RpcRequest request = (RpcRequest) obj;
            Class<?>[] paramsType = request.getParamsClazz();
            Object[] params = request.getParams();
            for(int i = 0; i < paramsType.length; i++) {
                params[i] = OBJECT_MAPPER.convertValue(params[i], paramsType[i]);
            }
            return clazz.cast(request);
        } else if(clazz == RpcResponse.class) {
            RpcResponse response = (RpcResponse) obj;
            Class<?> dataType = response.getDataType();
            response.setData(OBJECT_MAPPER.convertValue(response.getData(), dataType));
            return clazz.cast(response);
        }
        return null;
    }

}
